<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-pic"></i>
          活动管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 搜索栏 -->
    <div class="container">
      <div class="handle-box">
        <el-input v-model="searchForm.title" placeholder="活动标题" class="handle-input mr10" clearable />
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="primary" icon="el-icon-lx-add" @click="showAddActivity">新增活动</el-button>
      </div>
      <!-- 表格 -->
      <el-table :data="tableData" border class="table" ref="activityTable" header-cell-class-name="table-header">
        <el-table-column prop="id" label="活动ID" width="80" />
        <el-table-column label="发布者头像" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.publisherAvatar" :src="scope.row.publisherAvatar" style="width: 40px; height: 40px; border-radius: 50%" fit="cover" :preview-src-list="[scope.row.publisherAvatar]" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="发布者昵称/ID" width="150">
          <template #default="scope">
            <div v-if="scope.row.publisherName || scope.row.publisherId">{{ scope.row.publisherName || '-' }} / {{ scope.row.publisherId || '-' }}</div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="封面" width="100">
          <template #default="scope">
            <div v-if="scope.row.imgUrl || scope.row.videoUrl" style="display: flex; justify-content: center">
              <!-- 图片封面 -->
              <el-image v-if="scope.row.imgUrl" :src="scope.row.imgUrl" style="width: 60px; height: 60px; border-radius: 4px" fit="cover" :preview-src-list="[scope.row.imgUrl]" />
              <!-- 视频封面缩略图 -->
              <div v-else-if="scope.row.videoUrl" style="width: 60px; height: 60px; border-radius: 4px; background: #f5f5f5; display: flex; align-items: center; justify-content: center; cursor: pointer; border: 1px solid #ddd; position: relative" @click="openVideoDialog(scope.row.videoUrl)">
                <video :src="scope.row.videoUrl" style="width: 100%; height: 100%; object-fit: cover; border-radius: 4px" muted />
                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(0, 0, 0, 0.6); border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center">
                  <i class="el-icon-video-play" style="font-size: 12px; color: #fff"></i>
                </div>
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="轮播图" width="100">
          <template #default="scope">
            <span v-if="!scope.row.imgList || scope.row.imgList.length === 0">-</span>
            <el-button v-else type="primary" size="mini" @click="openMediaDialog(scope.row.carouselMediaList)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" width="200">
          <template #default="scope">
            <div class="content-cell">
              {{ scope.row.title || '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="内容" width="100">
          <template #default="scope">
            <el-button v-if="scope.row.activityDetails && scope.row.activityDetails.trim()" type="primary" size="mini" @click="viewContent(scope.row)">查看</el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="topic" label="话题" width="120">
          <template #default="scope">
            {{ scope.row.topic || '-' }}
          </template>
        </el-table-column> -->
        <el-table-column prop="paymentAmount" label="价格" width="100">
          <template #default="scope">
            {{ scope.row.paymentAmount ? `¥${scope.row.paymentAmount}` : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="activityLocation" label="位置" width="150">
          <template #default="scope">
            {{ scope.row.activityLocation || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="activityCondition1" label="是否支持退款" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.activityCondition1 === 1 ? 'success' : 'danger'">
              {{ scope.row.activityCondition1 === 1 ? '支持' : '不支持' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="activityCondition2" label="是否实名" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.activityCondition2 === 1 ? 'success' : 'info'">
              {{ scope.row.activityCondition2 === 1 ? '实名' : '非实名' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="signUpStartTime" label="报名开始时间" width="160">
          <template #default="scope">
            {{ dateFormat(scope.row.signUpStartTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="signUpEndTime" label="报名结束时间" width="160">
          <template #default="scope">
            {{ dateFormat(scope.row.signUpEndTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="activityTime" label="开始时间" width="160">
          <template #default="scope">
            {{ dateFormat(scope.row.activityTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="160">
          <template #default="scope">
            {{ dateFormat(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="showEditActivity(scope.row)">编辑</el-button>
            <el-button type="text" class="red" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="text" @click="addComment(scope.row)">添加评论</el-button>
            <el-button type="text" @click="viewComments(scope.row)">查看评论列表</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>
      </div>
    </div>

    <!-- 媒体预览弹窗 -->
    <el-dialog v-model="mediaDialog.visible" width="40%" title="媒体预览" append-to-body>
      <div style="display: flex; justify-content: center">
        <media-view v-if="mediaDialog.list.length" :list="mediaDialog.list" />
      </div>
    </el-dialog>

    <!-- 视频播放弹窗 -->
    <el-dialog v-model="videoDialog.visible" width="50%" title="视频播放" append-to-body @close="closeVideoDialog">
      <div style="display: flex; justify-content: center">
        <video v-if="videoDialog.url" :src="videoDialog.url" controls style="max-width: 100%; max-height: 60vh" ref="videoPlayer" @loadstart="onVideoLoadStart" @error="onVideoError"></video>
      </div>
    </el-dialog>

    <!-- 新建/编辑活动弹窗 -->
    <el-dialog v-model="addDialog.visible" :title="addDialog.isEdit ? '编辑活动' : '新增活动'" width="60%">
      <el-form :model="addDialog.form" label-width="120px">
        <el-form-item label="发布者">
          <div style="display: flex; align-items: center; gap: 10px">
            <el-input v-model="publisherDisplayText" :key="publisherDisplayText" placeholder="请选择发布者" readonly style="flex: 1" />
            <el-button @click="selectPublisher">选择发布者</el-button>
            <el-button v-if="addDialog.form.publisher" type="danger" @click="clearPublisher">清除</el-button>
          </div>
        </el-form-item>
        <el-form-item label="标题" required>
          <el-input v-model="addDialog.form.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动详情" required>
          <wang-editor v-model="addDialog.form.activityDetails" :height="400" placeholder="请输入活动详情..." ref="wangEditor" />
          <div class="form-tip">支持富文本编辑，可插入图片、视频等媒体内容</div>
        </el-form-item>
        <el-form-item label="活动位置" required>
          <div style="display: flex; align-items: center; gap: 10px">
            <el-input v-model="addDialog.form.activityLocation" placeholder="请输入活动位置" style="flex: 1" />
            <el-button @click="openMapSelector">选择位置</el-button>
          </div>
          <div v-if="addDialog.form.activityLocationLongitude && addDialog.form.activityLocationLatitude" style="margin-top: 5px; color: #606266; font-size: 13px">经纬度: {{ addDialog.form.activityLocationLongitude }}, {{ addDialog.form.activityLocationLatitude }}</div>
        </el-form-item>
        <el-form-item label="费用">
          <el-input v-model="addDialog.form.paymentAmount" placeholder="请输入费用" type="number" />
        </el-form-item>
        <el-form-item label="是否支持退款">
          <el-radio-group v-model="addDialog.form.activityCondition1">
            <el-radio :label="1">支持退款</el-radio>
            <el-radio :label="0">不支持退款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否实名">
          <el-radio-group v-model="addDialog.form.activityCondition2">
            <el-radio :label="1">实名</el-radio>
            <el-radio :label="0">非实名</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="报名开始时间" required>
          <el-date-picker v-model="addDialog.form.signUpStartTime" type="datetime" placeholder="选择报名开始时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="报名结束时间" required>
          <el-date-picker v-model="addDialog.form.signUpEndTime" type="datetime" placeholder="选择报名结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" @change="handleSignUpEndTimeChange" />
        </el-form-item>
        <el-form-item label="活动时间" required>
          <el-date-picker v-model="addDialog.form.activityTime" type="datetime" placeholder="选择活动时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <!-- <el-form-item label="创建时间">
          <el-date-picker v-model="addDialog.form.createTime" type="datetime" placeholder="创建时间"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;" />
        </el-form-item> -->
        <!-- <el-form-item label="话题">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-input :value="getTopicDisplayText()" placeholder="选择话题（可选）" readonly style="flex: 1;" />
            <el-button @click="selectTopic">选择话题</el-button>
            <el-button v-if="addDialog.form.selectedTopics.length > 0" type="danger" @click="clearTopic">清除</el-button>
          </div>
          <div v-if="addDialog.form.selectedTopics.length > 0" class="selected-topics">
            <el-tag v-for="topic in addDialog.form.selectedTopics" :key="topic.topicId" closable
              @close="removeTopicTag(topic)" class="topic-tag">
              {{ topic.topicName }}
            </el-tag>
          </div>
        </el-form-item> -->
        <el-form-item label="封面类型" required>
          <el-radio-group v-model="addDialog.form.coverType">
            <el-radio label="image">图片封面</el-radio>
            <el-radio label="video">视频封面</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="addDialog.form.coverType === 'image'" label="封面图片" required>
          <MediaUploader v-model="addDialog.form.imgList" :limit="1" accept-type="image" />
          <div class="form-tip">请上传活动封面图片</div>
        </el-form-item>
        <el-form-item v-if="addDialog.form.coverType === 'video'" label="封面视频" required>
          <MediaUploader v-model="addDialog.form.videoList" :limit="1" accept-type="video" />
          <div class="form-tip">请上传活动封面视频</div>
        </el-form-item>
        <el-form-item label="轮播图">
          <MediaUploader v-model="addDialog.form.imgs" :limit="9" accept-type="image" />
          <div class="form-tip">可上传最多9张轮播图片</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="addDialog.isEdit ? saveEdit() : saveAdd()">保存</el-button>
      </template>
    </el-dialog>

    <!-- 选择用户弹窗 -->
    <SelectUser v-model="selectUserVisible" :multiple="false" :selected-user-ids="addDialog.form.publisher ? [addDialog.form.publisher.userId] : []" @confirm="handleSelectUser" />

    <!-- 选择话题弹窗 -->
    <SelectTopic v-model="selectTopicVisible" :selected-data="addDialog.form.selectedTopics" @confirm="handleSelectTopic" />

    <!-- 地图选择器 -->
    <GetMap v-model="mapSelectorVisible" :default-lng="addDialog.form.activityLocationLongitude" :default-lat="addDialog.form.activityLocationLatitude" :default-address="addDialog.form.activityLocation" @confirm="handleMapSelection" />

    <!-- 内容预览弹窗 -->
    <el-dialog v-model="contentDialog.visible" :title="contentDialog.title" width="70%" append-to-body>
      <div class="content-preview">
        <wang-editor v-model="contentDialog.content" :height="400" :readOnly="true" ref="contentPreviewEditor" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import MediaUploader from '@/components/mediaUploader.vue'
import MediaView from '@/components/mediaVIew.vue'
import SelectUser from '@/components/selectUser.vue'
import SelectTopic from '@/components/selectTopic.vue'
import GetMap from '@/components/getMap.vue'
import WangEditor from '@/components/wang-editor.vue'
import { getActivities, addActivity, deleteActivity, updateActivity } from '@/api/content'
import { upload } from '@/api/index'

export default {
  name: 'ActivityManagement',
  components: {
    MediaView,
    MediaUploader,
    SelectUser,
    SelectTopic,
    GetMap,
    WangEditor,
  },
  data() {
    return {
      searchForm: {
        title: '',
      },
      tableData: [],
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      mediaDialog: {
        visible: false,
        list: [],
      },
      // 视频播放弹窗
      videoDialog: {
        visible: false,
        url: '',
      },
      addDialog: {
        visible: false,
        isEdit: false, // 是否为编辑模式
        editId: null, // 编辑的活动ID
        form: {
          title: '',
          activityDetails: '',
          activityLocation: '',
          activityLocationLatitude: '', // 活动地点纬度
          activityLocationLongitude: '', // 活动地点经度
          activityTime: '',
          paymentAmount: '',
          signUpStartTime: '',
          signUpEndTime: '',
          activityCondition1: 0, // 是否支持退款
          activityCondition2: 0, // 是否实名
          coverType: 'image', // 封面类型：image 或 video
          imgList: [],
          videoList: [],
          imgs: [], // 轮播图列表
          publisher: null,
          selectedTopics: [],
          topic: '',
          createTime: '', // 创建时间
        },
      },
      // 内容预览弹窗
      contentDialog: {
        visible: false,
        content: '',
        title: '',
      },
      // 用户选择弹窗
      selectUserVisible: false,
      // 话题选择弹窗
      selectTopicVisible: false,
      // 地图选择弹窗
      mapSelectorVisible: false,
    }
  },
  computed: {
    publisherDisplayText() {
      return this.addDialog.form.publisher ? `${this.addDialog.form.publisher.nickname} (${this.addDialog.form.publisher.userId})` : ''
    },
  },
  watch: {
    // 监听视频弹窗关闭，确保视频停止播放
    'videoDialog.visible'(newVal) {
      if (!newVal) {
        this.$nextTick(() => {
          if (this.$refs.videoPlayer) {
            this.$refs.videoPlayer.pause()
            this.$refs.videoPlayer.currentTime = 0
          }
        })
      }
    },
  },
  mounted() {
    this.getData()
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    formatDateTime(date) {
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },

    handleSearch() {
      // 搜索时重置到第一页
      this.pagination.currentPage = 1
      this.getData()
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.getData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.getData()
    },
    buildSearchParams() {
      const params = {
        // 必须的分页参数
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage,
      }

      // 根据搜索表单构建查询参数
      if (this.searchForm.title) {
        params.title = this.searchForm.title
      }

      return params
    },
    buildMediaList(item) {
      const mediaList = []

      // 处理图片
      if (item.imgUrl) {
        mediaList.push({
          type: 'image',
          url: item.imgUrl,
        })
      }

      // 处理视频
      if (item.videoUrl) {
        mediaList.push({
          type: 'video',
          url: item.videoUrl,
        })
      }

      return mediaList
    },

    // 构建轮播图媒体列表
    buildCarouselMediaList(item) {
      const mediaList = []

      if (item.imgList && Array.isArray(item.imgList)) {
        item.imgList.forEach((imgUrl) => {
          if (imgUrl) {
            mediaList.push({
              type: 'image',
              url: imgUrl,
            })
          }
        })
      }

      return mediaList
    },

    // 查看内容
    viewContent(row) {
      console.log('viewContent - row数据:', row)
      console.log('viewContent - activityDetails:', row.activityDetails)
      this.contentDialog.title = row.title || '活动内容'
      this.contentDialog.content = row.activityDetails || ''
      this.contentDialog.visible = true
      console.log('contentDialog设置后:', this.contentDialog)

      // 确保富文本编辑器正确加载内容
      this.$nextTick(() => {
        if (this.$refs.contentPreviewEditor && row.activityDetails) {
          // 延迟设置内容，确保编辑器已经初始化
          setTimeout(() => {
            if (this.$refs.contentPreviewEditor.editor && this.$refs.contentPreviewEditor.isReady) {
              this.$refs.contentPreviewEditor.editor.txt.html(row.activityDetails)
            }
          }, 500)
        }
      })
    },
    async getData() {
      try {
        const params = this.buildSearchParams()
        const response = await getActivities(params)

        if (response && response.data) {
          // 将API返回的数据映射到表格需要的格式
          this.tableData = response.data.rows.map((item) => ({
            id: item.id,
            city: item.city || '未知', // 活动所属城市
            publisherAvatar: item.publisherAvatar || '', // 发布者头像
            publisherName: item.publisherName || '', // 发布者昵称
            publisherId: item.publisherId || '', // 发布者ID
            imgUrl: item.imgUrl,
            videoUrl: item.videoUrl,
            mediaList: this.buildMediaList(item),
            imgList: item.imgList || [], // 轮播图
            carouselMediaList: this.buildCarouselMediaList(item), // 轮播图媒体列表
            title: item.title,
            activityDetails: item.activityDetails,
            topic: item.topic || '', // 话题
            paymentAmount: item.paymentAmount,
            activityLocation: item.activityLocation,
            activityCondition1: item.activityCondition1,
            activityCondition2: item.activityCondition2,
            signUpStartTime: item.signUpStartTime,
            signUpEndTime: item.signUpEndTime,
            activityTime: item.activityTime,
            createTime: item.createTime,
            // 保留原始数据用于编辑
            _original: item,
          }))

          // 更新总数（如果接口返回了总数）
          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total
          }
        }
      } catch (error) {
        console.error('获取活动数据失败:', error)
        this.$message.error('获取活动数据失败')
      }
    },
    openMediaDialog(list) {
      this.mediaDialog.list = list || []
      this.mediaDialog.visible = true
    },
    // 打开视频播放弹窗
    openVideoDialog(videoUrl) {
      this.videoDialog.url = videoUrl
      this.videoDialog.visible = true
    },
    // 关闭视频播放弹窗
    closeVideoDialog() {
      // 暂停并重置视频
      if (this.$refs.videoPlayer) {
        this.$refs.videoPlayer.pause()
        this.$refs.videoPlayer.currentTime = 0
      }
      this.videoDialog.visible = false
      this.videoDialog.url = ''
    },
    // 视频开始加载
    onVideoLoadStart() {
      console.log('视频开始加载')
    },
    // 视频加载错误
    onVideoError(error) {
      console.error('视频加载失败:', error)
      this.$message.error('视频加载失败，请检查视频链接是否有效')
    },
    async saveEdit() {
      try {
        // 验证必填项
        if (!this.addDialog.form.title.trim()) {
          this.$message.error('请输入活动标题')
          return
        }

        // 直接从富文本编辑器获取内容进行验证
        let activityDetails = ''
        if (this.$refs.wangEditor) {
          activityDetails = this.$refs.wangEditor.getContent()
        } else {
          activityDetails = this.addDialog.form.activityDetails || ''
        }

        if (!activityDetails.trim()) {
          this.$message.error('请输入活动详情')
          return
        }
        if (!this.addDialog.form.activityLocation.trim()) {
          this.$message.error('请输入活动位置')
          return
        }
        if (!this.addDialog.form.signUpStartTime) {
          this.$message.error('请选择报名开始时间')
          return
        }
        if (!this.addDialog.form.signUpEndTime) {
          this.$message.error('请选择报名结束时间')
          return
        }
        if (!this.addDialog.form.activityTime) {
          this.$message.error('请选择活动时间')
          return
        }

        // 验证封面
        if (this.addDialog.form.coverType === 'image' && (!this.addDialog.form.imgList || this.addDialog.form.imgList.length === 0)) {
          this.$message.error('请上传封面图片')
          return
        }
        if (this.addDialog.form.coverType === 'video' && (!this.addDialog.form.videoList || this.addDialog.form.videoList.length === 0)) {
          this.$message.error('请上传封面视频')
          return
        }

        // 验证活动时间是否晚于报名结束时间
        const signUpEndTime = new Date(this.addDialog.form.signUpEndTime)
        const activityTime = new Date(this.addDialog.form.activityTime)
        if (activityTime <= signUpEndTime) {
          this.$message.warning('活动时间应晚于报名结束时间')
          return
        }

        // 构建编辑参数
        const params = await this.buildActivityParams()
        params.id = this.addDialog.editId

        await updateActivity(params)

        this.$message.success('编辑活动成功')
        this.addDialog.visible = false
        this.getData()
      } catch (error) {
        console.error('编辑活动失败:', error)
        this.$message.error('编辑活动失败')
      }
    },
    handleDelete(row) {
      this.$confirm('确定要删除该活动吗？', '提示', { type: 'warning' })
        .then(async () => {
          try {
            // 构建删除参数
            const delDTO = {
              id: row.id,
            }

            await deleteActivity(delDTO)

            this.$message.success('删除活动成功')
            this.getData()
          } catch (error) {
            console.error('删除活动失败:', error)
            this.$message.error('删除活动失败')
          }
        })
        .catch(() => {
          // 用户取消删除
        })
    },
    viewComments(row) {
      // TODO: 查看评论列表，暂不实现
      this.$message.info('查看评论列表功能暂未实现')
    },
    addComment(row) {
      // TODO: 添加评论，暂不实现
      this.$message.info('添加评论功能暂未实现')
    },
    showAddActivity() {
      this.addDialog.visible = true
      this.addDialog.isEdit = false
      this.addDialog.editId = null

      // 设置默认时间
      const now = new Date()
      const signUpEndDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) // 默认报名结束时间为一周后
      const activityDate = new Date(signUpEndDate.getTime() + 24 * 60 * 60 * 1000) // 活动时间比报名结束时间晚一天

      this.addDialog.form = {
        title: '',
        activityDetails: '',
        activityLocation: '',
        activityLocationLatitude: '', // 活动地点纬度
        activityLocationLongitude: '', // 活动地点经度
        activityTime: this.formatDateTime(activityDate), // 活动时间比报名结束时间晚一天
        paymentAmount: '',
        signUpStartTime: this.formatDateTime(now),
        signUpEndTime: this.formatDateTime(signUpEndDate),
        activityCondition1: 0, // 是否支持退款
        activityCondition2: 0, // 是否实名
        coverType: 'image', // 封面类型：image 或 video
        imgList: [],
        videoList: [],
        imgs: [], // 轮播图列表
        // 预设发布者信息，但可以自由选择
        publisher: {
          userId: '0f56366a8054fe012b04ed9b2e3d1201',
          nickname: '铂时官方',
          userPic: '',
        },
        selectedTopics: [],
        topic: '',
        createTime: this.formatDateTime(now), // 创建时间，默认为当前时间
      }

      // 重置富文本编辑器内容
      this.$nextTick(() => {
        if (this.$refs.wangEditor) {
          // 延迟重置，确保编辑器已经初始化
          setTimeout(() => {
            if (this.$refs.wangEditor.editor && this.$refs.wangEditor.isReady) {
              this.$refs.wangEditor.editor.txt.html('')
            } else if (this.$refs.wangEditor.setContent) {
              // 如果有setContent方法，使用该方法
              this.$refs.wangEditor.setContent('')
            }
          }, 300)
        }
      })
    },
    showEditActivity(row) {
      console.log('编辑活动 - row数据:', row)
      console.log('编辑活动 - original数据:', row._original)

      this.addDialog.isEdit = true
      this.addDialog.editId = row.id

      // 填充编辑数据
      const original = row._original

      // 处理轮播图
      const carouselImgList = []
      if (row.imgList && Array.isArray(row.imgList)) {
        row.imgList.forEach((imgUrl) => {
          if (imgUrl) {
            carouselImgList.push({
              url: imgUrl,
              type: 'image/jpeg',
              name: 'carousel-image.jpg',
            })
          }
        })
      }

      this.addDialog.form = {
        title: row.title || '',
        activityDetails: row.activityDetails || '',
        activityLocation: row.activityLocation || '',
        activityLocationLatitude: original.activityLocationLatitude || '', // 活动地点纬度
        activityLocationLongitude: original.activityLocationLongitude || '', // 活动地点经度
        activityTime: row.activityTime ? this.formatDateTime(new Date(row.activityTime)) : '',
        paymentAmount: row.paymentAmount || '',
        signUpStartTime: row.signUpStartTime ? this.formatDateTime(new Date(row.signUpStartTime)) : '',
        signUpEndTime: row.signUpEndTime ? this.formatDateTime(new Date(row.signUpEndTime)) : '',
        activityCondition1: row.activityCondition1, // 是否支持退款
        activityCondition2: row.activityCondition2, // 是否实名
        // 根据现有数据确定封面类型
        coverType: row.videoUrl ? 'video' : 'image',
        // 处理图片
        imgList: row.imgUrl
          ? [
              {
                url: row.imgUrl,
                type: 'image/jpeg',
                name: 'image.jpg',
              },
            ]
          : [],
        // 处理视频
        videoList: row.videoUrl
          ? [
              {
                url: row.videoUrl,
                type: 'video/mp4',
                name: 'video.mp4',
              },
            ]
          : [],
        // 轮播图列表
        imgs: carouselImgList,
        publisher: {
          userId: row.publisherId || '',
          nickname: row.publisherName || '',
          userPic: row.publisherAvatar || '',
        },
        selectedTopics: row.topic
          ? [
              {
                topicId: original.topicId || '',
                topicName: row.topic,
              },
            ]
          : [],
        topic: row.topic || '',
        createTime: row.createTime ? this.formatDateTime(new Date(row.createTime)) : this.formatDateTime(new Date()), // 创建时间
      }

      this.addDialog.visible = true

      // 确保富文本编辑器正确加载内容
      this.$nextTick(() => {
        if (this.$refs.wangEditor && row.activityDetails) {
          // 延迟设置内容，确保编辑器已经初始化
          setTimeout(() => {
            if (this.$refs.wangEditor.editor && this.$refs.wangEditor.isReady) {
              this.$refs.wangEditor.editor.txt.html(row.activityDetails)
            }
          }, 500)
        }
      })
    },
    async buildActivityParams() {
      const form = this.addDialog.form

      // 处理图片
      let imgUrl = ''
      if (form.imgList && form.imgList.length > 0) {
        imgUrl = form.imgList[0].url
      }

      // 处理视频
      let videoUrl = ''
      if (form.videoList && form.videoList.length > 0) {
        videoUrl = form.videoList[0].url
      }

      // 直接从富文本编辑器组件获取最新内容
      let activityDetails = ''
      if (this.$refs.wangEditor) {
        activityDetails = this.$refs.wangEditor.getContent()
        console.log('直接从编辑器获取的富文本内容:', activityDetails)
      } else {
        activityDetails = form.activityDetails || ''
        console.warn('未能获取到富文本编辑器引用，使用表单中的值')
      }

      // 处理轮播图
      let carouselImgs = []
      if (form.imgs && form.imgs.length > 0) {
        carouselImgs = form.imgs.map((item) => item.url)
      }

      // 构建活动参数
      return {
        // 发布者信息
        publisherId: form.publisher?.userId || '',
        publisherName: form.publisher?.nickname || '',

        // 活动基本信息
        title: form.title || '',
        activityDetails: activityDetails,
        activityLocation: form.activityLocation || '',
        activityLocationLatitude: form.activityLocationLatitude || '', // 活动地点纬度
        activityLocationLongitude: form.activityLocationLongitude || '', // 活动地点经度
        activityTime: form.activityTime || '',

        // 报名相关
        signUpStartTime: form.signUpStartTime ? new Date(form.signUpStartTime).getTime() : '',
        signUpEndTime: form.signUpEndTime ? new Date(form.signUpEndTime).getTime() : '',

        // 条件相关
        activityCondition1: form.activityCondition1, // 是否支持退款
        activityCondition2: form.activityCondition2, // 是否实名

        // 价格
        paymentAmount: form.paymentAmount || '',

        // 媒体相关
        imgUrl: imgUrl,
        videoUrl: videoUrl,
        imgs: carouselImgs, // 轮播图

        // // 话题相关
        // topic: form.topic || '',
        // topicId: form.selectedTopics.length > 0 ? form.selectedTopics[0].topicId : '',

        // 其他必要字段
        city: '', // 城市暂时留空，可以后续添加
        // createTime: form.createTime || this.formatDateTime(new Date()),
      }
    },
    async saveAdd() {
      try {
        // 验证必填项
        if (!this.addDialog.form.title.trim()) {
          this.$message.error('请输入活动标题')
          return
        }

        // 直接从富文本编辑器获取内容进行验证
        let activityDetails = ''
        if (this.$refs.wangEditor) {
          activityDetails = this.$refs.wangEditor.getContent()
        } else {
          activityDetails = this.addDialog.form.activityDetails || ''
        }

        if (!activityDetails.trim()) {
          this.$message.error('请输入活动详情')
          return
        }
        if (!this.addDialog.form.activityLocation.trim()) {
          this.$message.error('请输入活动位置')
          return
        }
        if (!this.addDialog.form.signUpStartTime) {
          this.$message.error('请选择报名开始时间')
          return
        }
        if (!this.addDialog.form.signUpEndTime) {
          this.$message.error('请选择报名结束时间')
          return
        }
        if (!this.addDialog.form.activityTime) {
          this.$message.error('请选择活动时间')
          return
        }

        // 验证封面
        if (this.addDialog.form.coverType === 'image' && (!this.addDialog.form.imgList || this.addDialog.form.imgList.length === 0)) {
          this.$message.error('请上传封面图片')
          return
        }
        if (this.addDialog.form.coverType === 'video' && (!this.addDialog.form.videoList || this.addDialog.form.videoList.length === 0)) {
          this.$message.error('请上传封面视频')
          return
        }

        // 验证活动时间是否晚于报名结束时间
        const signUpEndTime = new Date(this.addDialog.form.signUpEndTime)
        const activityTime = new Date(this.addDialog.form.activityTime)
        if (activityTime <= signUpEndTime) {
          this.$message.warning('活动时间应晚于报名结束时间')
          return
        }

        // 构建新增活动的参数
        const params = await this.buildActivityParams()

        await addActivity(params)

        this.$message.success('新增活动成功')
        this.addDialog.visible = false
        this.getData()
      } catch (error) {
        console.error('新增活动失败:', error)
        this.$message.error('新增活动失败')
      }
    },
    selectPublisher() {
      this.selectUserVisible = true
    },
    clearPublisher() {
      this.addDialog.form.publisher = null
    },
    handleSelectUser(selectedUsers) {
      if (selectedUsers && selectedUsers.length > 0) {
        this.addDialog.form.publisher = selectedUsers[0]
      }
    },
    selectTopic() {
      this.selectTopicVisible = true
    },
    clearTopic() {
      this.addDialog.form.selectedTopics = []
      this.addDialog.form.topic = ''
    },
    handleSelectTopic(selectedTopics) {
      this.addDialog.form.selectedTopics = selectedTopics
      // 更新topic字段为第一个话题的名称（兼容原有逻辑）
      this.addDialog.form.topic = selectedTopics.length > 0 ? selectedTopics[0].topicName : ''
    },
    removeTopicTag(topicToRemove) {
      this.addDialog.form.selectedTopics = this.addDialog.form.selectedTopics.filter((topic) => topic.topicId !== topicToRemove.topicId)
      // 更新topic字段
      this.addDialog.form.topic = this.addDialog.form.selectedTopics.length > 0 ? this.addDialog.form.selectedTopics[0].topicName : ''
    },
    getTopicDisplayText() {
      const count = this.addDialog.form.selectedTopics.length
      if (count === 0) return ''
      if (count === 1) return this.addDialog.form.selectedTopics[0].topicName
      return `已选择 ${count} 个话题`
    },

    // 打开地图选择器
    openMapSelector() {
      this.mapSelectorVisible = true
    },

    // 处理地图选择结果
    handleMapSelection(location) {
      console.log(location, 'location')
      if (location) {
        this.addDialog.form.activityLocation = location.address
        this.addDialog.form.activityLocationLatitude = location.lat // 活动地点纬度
        this.addDialog.form.activityLocationLongitude = location.lng // 活动地点经度
      }
    },

    // 监听报名结束时间变化，自动更新活动时间为晚一天
    handleSignUpEndTimeChange() {
      if (this.addDialog.form.signUpEndTime) {
        const signUpEndDate = new Date(this.addDialog.form.signUpEndTime)
        const activityDate = new Date(signUpEndDate.getTime() + 24 * 60 * 60 * 1000) // 活动时间比报名结束时间晚一天
        this.addDialog.form.activityTime = this.formatDateTime(activityDate)
      }
    },
  },
}
</script>

<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.green {
  color: #0ab618;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  height: 60px;
  width: 60px;
}

.crop-demo {
  display: flex;
  align-items: flex-end;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 148px;
  height: 148px;

  .pre-img {
    width: 146px;
    height: 146px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 5px;
    object-fit: cover;
  }

  .crop-input {
    position: absolute;
    width: 148px;
    height: 148px;
    left: 0px;
    top: 0px;
    opacity: 0;
    cursor: pointer;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
}

.picPreview {
  width: 100%;
}

.mb10 {
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.content-cell {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 20px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}

::v-deep .el-date-editor {
  margin-right: 10px;
  width: 300px;
}

.selected-topics {
  margin-top: 8px;
}

.topic-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.content-preview {
  max-height: 70vh;
  overflow-y: auto;
  padding: 10px;
}

.content-preview img {
  max-width: 100%;
}

.content-preview video {
  max-width: 100%;
}
</style>
